# -*- coding: utf-8 -*-
from django.template import RequestContext, Context
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect
from django.core.mail import EmailMessage
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, logout, login as authlogin
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
import django.contrib.auth.views

def news(request):
    from models import vaga, areavaga
    from forms import emailForm

    vaga = vaga.objects.all().order_by('pub_date')
    areavaga = areavaga.objects.all()

    if request.method == 'POST':
        form = emailForm(request.POST)
        if form.is_valid():
            novo = form.save()
    else:
        form = emailForm()

    return render_to_response('ingenium/newsletter.html', locals(), context_instance=RequestContext(request))


def homepage(request):
    from models import vaga,areavaga,curso
    from publicacoes.models import Noticias,Eventos,Destaques,Parceiros,Artigo,Enquete,Alternativa
    from publicidade.models import Publicidade
    from django.conf import settings
    from datetime import datetime

    curso = curso.objects.filter(ativar__exact='True')[:1]
    vaga = vaga.objects.all().order_by('-pub_date')
    context = {'MEDIA_URL': settings.MEDIA_URL}
    noticias = Noticias.objects.all().order_by('-publicar', '-publicacao')[:3]
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar', '-publicacao')[:3]
    parceiros = Parceiros.objects.all()
    artigo = Artigo.objects.all().order_by('-publicar', '-publicacao')[:4]
    areavaga = areavaga.objects.all().order_by('-qtdvagas')
    enquete = Enquete.objects.all().select_related().order_by('-data_publicacao')
    publicidade = Publicidade.objects.filter(data_entrada__lte=datetime.now()).order_by('-data_entrada')
    bannerextra = Publicidade.objects.filter(publicar__exact = 'True',posicao__exact = '2',data_entrada__lte=datetime.now()).order_by('-data_entrada')
    bannerextra2 = Publicidade.objects.filter(publicar__exact = 'True',posicao__exact = '3',data_entrada__lte=datetime.now()).order_by('-data_entrada')
    tijolo1 = Publicidade.objects.filter(publicar__exact = 'True',posicao__exact = '4',data_entrada__lte=datetime.now()).order_by('-data_entrada')
    publifoto =Publicidade.objects.filter(publicar__exact = 'True', posicao__exact = '1', data_entrada__lte=datetime.now()).order_by('-data_entrada')
    if request.method == 'POST':
      if request.POST['alternativa']:
        voto = Alternativa.objects.get(pk=request.POST['alternativa'])
        voto.votos += 1
        voto.save()

    return render_to_response('ingenium/index.html', locals(), context_instance=RequestContext(request))
    
def eventos(request):
    from django.conf import settings
    from models import areavaga,vaga
    from publicacoes.models import Eventos,Destaques
    from datetime import datetime
    context = {'MEDIA_URL': settings.MEDIA_URL}
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('diadoevento')
    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    vaga = vaga.objects.all().order_by('-pub_date')[:3]
    paginator = Paginator(eventos, 20)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        eventos = paginator.page(page)
    except (EmptyPage, InvalidPage):
        eventos = paginator.page(paginator.num_pages)
		
    return render_to_response('ingenium/eventos.html', locals(), context_instance=RequestContext(request))

def artigos(request):
    from django.conf import settings
    from publicacoes.models import Artigo,Destaques
    from ingenium.models import areavaga,vaga

    context = {'MEDIA_URL': settings.MEDIA_URL}
	
    artigo = Artigo.objects.all().order_by('-publicar','-publicacao')
    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    vaga = vaga.objects.all().order_by('-pub_date')[:3]
    paginator = Paginator(artigo, 20)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        artigo = paginator.page(page)
    except (EmptyPage, InvalidPage):
        artigo = paginator.page(paginator.num_page)

		
    return render_to_response('ingenium/artigos.html', locals(), context_instance=RequestContext(request))

@csrf_protect
def artigo(request, slug):
    from publicacoes.models import Eventos,Destaques,Artigo
    from models import areavaga
    from datetime import datetime

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    artigo = Artigo.objects.get(slug=slug)

    return render_to_response('ingenium/artigo.html', locals(), context_instance=RequestContext(request))

def ultimasvagas(request):
    from models import vagaempresa, areavaga, procura, usuario
    areavaga = areavaga.objects.all()
    procuras = procura.objects.all()
    usuarios = usuario.objects.all()
    v = vagaempresa.objects.all().order_by('-data')
    return render_to_response('ingenium/ultimasvagas.html', locals(), context_instance=RequestContext(request))

def vaga(request, vaga_id):
    from models import areavaga,vagaempresa

    areavaga = areavaga.objects.all()
    vagaempresa = vagaempresa.objects.get(id=vaga_id)

    return render_to_response('ingenium/vaga.html', locals(), context_instance=RequestContext(request))


def cadastrarcurriculo1(request):
    from models import areavaga
    from forms import usuarioForm

    areavaga = areavaga.objects.all()
    c = None

    if request.method == 'POST':
        form = usuarioForm(request.POST, request.FILES)
        if form.is_valid():
            novo_usuario = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi39.tinypic.com/35d5now.jpg'/></a>"
            msge = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msge.content_subtype = "html"
            msge.send()
            return render_to_response('ingenium/cadastro-concluido.html',locals(), context_instance=RequestContext(request))
            
    else:
        form = usuarioForm()
        c = Context({'nome':request.GET['nome'], 'tel':request.GET['telefone'], 'mail':request.GET['mail']})

    return render_to_response('ingenium/cadastrarcurriculo1.html', locals(), context_instance=RequestContext(request,c))

def cadastrarcurriculo(request):
    from models import areavaga
    from forms import usuarioForm

    areavaga = areavaga.objects.all()

    if request.method == 'POST':
        form = usuarioForm(request.POST, request.FILES)
        if form.is_valid():
            novo_usuario = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi39.tinypic.com/35d5now.jpg'/></a>"
            msge = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msge.content_subtype = "html"
            msge.send()
            return render_to_response('ingenium/cadastro-concluido.html',locals(), context_instance=RequestContext(request))
    else:
        form = usuarioForm()
    return render_to_response('ingenium/cadastrarcurriculo1.html', locals(), context_instance=RequestContext(request))

def cadastrarempresa(request):
    from ingenium.models import areavaga,vaga,empresa
    from forms import empresaForm

    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all()
    if request.method == 'POST':
        form = empresaForm(request.POST, request.FILES)
        username = request.POST['username']
        valida = 0
        erro = ''
        use = empresa.objects.filter(username__exact = username)
        if use:
            valida = 1
            erro = 'Já existe uma empresa com esse username!'
        if form.is_valid() and valida == 0:
            nova_empresa = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi41.tinypic.com/fbkdb4.jpg'/></a>"
            msge = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msge.content_subtype = "html"
            msge.send()
            return render_to_response('ingenium/cadastro-concluido.html',locals(), context_instance=RequestContext(request,{'erro':erro,}))
    else:
        form = empresaForm()
        error = 'Verifique se seu CNPJ ou Login est�corretos!'
    return render_to_response('ingenium/cadastrar-empresa.html', locals(), context_instance=RequestContext(request))



def duvidas(request):
    from ingenium.models import areavaga, duvidafrequente

    frequenteduvida = duvidafrequente.objects.all()
    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/duvidas.html', locals(), context_instance=RequestContext(request))

def empresaservico(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/empresaservico.html', locals(), context_instance=RequestContext(request))

def abertos(request):
    from ingenium.models import curso

    aberto = curso.objects.filter(destinado__exact=1).order_by('-pub_date')
    return render_to_response('ingenium/abertos.html', locals(), context_instance=RequestContext(request))

def incompany(request):
    from ingenium.models import curso

    incompany = curso.objects.filter(destinado__exact=0).order_by('-pub_date')
    return render_to_response('ingenium/incompany.html', locals(), context_instance=RequestContext(request))

def servicos(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/servicos.html', locals(), context_instance=RequestContext(request))


def vantagens(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/vantagens.html', locals(), context_instance=RequestContext(request))
	
def treinamento(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/treinamento.html', locals(), context_instance=RequestContext(request))
	
def aviso(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/aviso.html', locals(), context_instance=RequestContext(request))

def imprensa(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/imprensa.html', locals(), context_instance=RequestContext(request))

def carta(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/carta-apresentacao.html', locals(), context_instance=RequestContext(request))

def analise(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/analise-curriculo.html', locals(), context_instance=RequestContext(request))


def politica(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/politica.html', locals(), context_instance=RequestContext(request))

def sobre(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/sobre.html', locals(), context_instance=RequestContext(request))

def fotosgalaxy(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/fotosgalaxy.html', locals(), context_instance=RequestContext(request))

def publicidade(request):
    from ingenium.models import areavaga

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/publicidade.html', locals(), context_instance=RequestContext(request))

@login_required
def usuarioCadastro(request, user_id):
    from ingenium.models import areavaga,usuario

    areavaga = areavaga.objects.all()
    user = usuario.objects.get(id=user_id, user=request.user,)
    return render_to_response('ingenium/curriculo.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioCurriculo(request,user_id):
    from ingenium.models import usuario, areavaga
    from forms import ateraruForm
    u = usuario.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = ateraruForm(request.POST,request.FILES, instance=u)

        if form.is_valid():
            u = form.save()

            if u:
                return HttpResponseRedirect(reverse('ingenium.views.usuarioDashboard', args=[u.id]))
    else:
        form = ateraruForm(instance=u)

    return render_to_response('ingenium/painel-usuario-curriculo.html',locals() ,context_instance=RequestContext(request))

@login_required
def usuarioCursos(request, user_id):
    from models import areavaga,usuario
    from publicacoes.models import Eventos
    from datetime import datetime

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
    u = usuario.objects.get(pk=user_id, user=request.user,)

    return render_to_response('ingenium/painel-usuario-cursos.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioDashboard(request, user_id):
    from models import usuario, areavaga, procura, vaga
    from mensagens.models import mensagemUsuario
    from datetime import datetime
    from publicacoes.models import Eventos
    areavaga = areavaga.objects.all().order_by('-qtdvagas')
    ar = procura.objects.filter(nome__id__exact = user_id)
    ab = ar.values('vaga')
    vg = vaga.objects.exclude(id__in = ab)
    u = usuario.objects.get(pk=user_id, user=request.user,)
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')[:5]
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now()).order_by('-data')

    return render_to_response('ingenium/painel-usuario-dashboard.html', locals(),context_instance=RequestContext(request))

@login_required
def usuariosugestao(request, user_id):
    from ingenium.models import usuario, areavaga
    from forms import FormContato
    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=user_id, user=request.user,)

    if request.method == 'POST':
        form = FormContato(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = FormContato()
    else:
        form = FormContato()
    return render_to_response('ingenium/painel-usuario-sugestao.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioInterna(request, user_id):
    from ingenium.models import usuario,areavaga
    from mensagens.models import mensagemUsuario
    from datetime import datetime

    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=user_id, user=request.user,)
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now()).order_by('-data')
    return render_to_response('ingenium/painel-usuario-interna.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioMensagens(request, cod):
    from ingenium.models import usuario,areavaga
    from mensagens.models import mensagemUsuario
    from datetime import datetime

    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=cod, user=request.user,)
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now()).order_by('-data')

    return render_to_response('ingenium/painel-usuario-mensagens.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioPerguntas(request, user_id):
    from ingenium.models import usuario,areavaga
    u = usuario.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()

    return render_to_response('ingenium/painel-usuario-perguntas.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioRelatorio(request, user_id):
    from ingenium.models import usuario
    u = usuario.objects.get(pk=user_id, user=request.user,)

    return render_to_response('ingenium/painel-usuario-relatorio.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaVagas(request,cad):
    from ingenium.models import empresa,areavaga
    from forms import vagaForm
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=cad, user=request.user,)

    if request.method == 'POST':
        form = vagaForm(request.POST)
        if form.is_valid():
            nova_vaga = form.save()
            return render_to_response('ingenium/painel-empresa-dashboard.html',locals(), context_instance=RequestContext(request,{'cad':cad}))
    else:
        form = vagaForm()

    return render_to_response('ingenium/painel-empresa-cadastrar-vagas.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaInterna(request, user_id):
    from ingenium.models import empresa, areavaga
    from mensagens.models import mensagemEmpresa
    from datetime import datetime

    areavaga = areavaga.objects.all()   
    e = empresa.objects.get(pk=user_id, user=request.user,)
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now()).order_by('-data')
    return render_to_response('ingenium/painel-empresa-interna.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaCadastro(request,user_id):
    from models import empresa, areavaga
    from forms import altempForm

    e = empresa.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = altempForm(request.POST,request.FILES, instance=e)

        if form.is_valid():
            e = form.save()

            if e:
                return HttpResponseRedirect(reverse('ingenium.views.empresaDashboard', args=[e.id]))
    else:
        form = altempForm(instance=e)

    return render_to_response('ingenium/painel-empresa-cadastro.html',locals() ,context_instance=RequestContext(request))

@login_required
def empresaDashboard(request, dash_id):
    from models import vaga,areavaga,empresa,requisicao
    from publicacoes.models import Eventos
    from mensagens.models import mensagemEmpresa
    from datetime import datetime

    areavaga = areavaga.objects.all()
    vg = vaga.objects.all()
    e = empresa.objects.get(pk=dash_id, user=request.user,)
    req = requisicao.objects.filter(empresa__exact=dash_id)

    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')[:5]
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now()).order_by('-data')

    return render_to_response('ingenium/painel-empresa-dashboard.html', locals(),context_instance=RequestContext(request,{'req':req}))

@login_required
def empresaGerenciar(request, vaga_id):
    from ingenium.models import empresa,requisicao,areavaga
    areavaga = areavaga.objects.all()

    e = empresa.objects.get(pk=vaga_id, user=request.user,)
    req = requisicao.objects.filter(empresa__exact=vaga_id)

    return render_to_response('ingenium/painel-empresa-gerenciar-vagas.html', locals(),context_instance=RequestContext(request,{'req':req}))

@login_required
def empresaRelatorio(request, rel):
    from ingenium.models import areavaga,empresa,vagaempresa,selecao

    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=rel, user=request.user,)
    email = request.user
    empres = ''
    quant = 0
    selec = ''
    empre = vagaempresa.objects.filter(empresa__id__exact = rel)
    quant = empre.count()
    if quant > 0:
            selec = selecao.objects.filter(recrutamento__vagaempresa__empresa__id__exact = rel)


    return render_to_response('ingenium/painel-empresa-relatorios.html', locals(),context_instance=RequestContext(request,{'empre':empre,'selec':selec,'quant':quant,}))

@login_required
def empresaSugestao(request, user_id):
    from ingenium.models import areavaga,empresa
    from forms import SugestaoForm
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=user_id, user=request.user,)

    if request.method == 'POST':
        form = SugestaoForm(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = SugestaoForm()
    else:
        form = SugestaoForm()
    return render_to_response('ingenium/painel-empresa-sugestao.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaMensagens(request, cod):
    from ingenium.models import empresa,areavaga
    from mensagens.models import mensagemEmpresa
    from datetime import datetime

    e = empresa.objects.get(pk=cod, user=request.user)
    areavaga = areavaga.objects.all()
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now()).order_by('-data')

    return render_to_response('ingenium/painel-empresa-mensagens.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaCursos(request, curso_id):
    from ingenium.models import empresa, areavaga
    from publicacoes.models import Eventos
    from datetime import datetime

    e = empresa.objects.get(pk=curso_id, user=request.user,)
    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')

    return render_to_response('ingenium/painel-empresa-cursos.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaPerguntas(request,per):
    from ingenium.models import areavaga,empresa

    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=per, user=request.user,)

    return render_to_response('ingenium/painel-empresa-perguntas.html', locals(),context_instance=RequestContext(request))


def destaques(request):
    from publicacoes.models import Destaques,Eventos,Noticias
    from models import areavaga,vaga
    from datetime import datetime

    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all().order_by('-pub_date')
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')
    noticias = Noticias.objects.all().order_by('-publicar','-publicacao')[:3]
    paginator = Paginator(destaques, 15)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        destaques = paginator.page(page)
    except (EmptyPage, InvalidPage):
        destaques = paginator.page(paginator.num_page)

	
    return render_to_response('ingenium/destaques.html', locals(), context_instance=RequestContext(request))	

@csrf_protect
def destaque(request, slug):
    from publicacoes.models import Destaques,Eventos,Noticias
    from models import areavaga
    from datetime import datetime

    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.get(slug=slug)
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    noticias = Noticias.objects.all().order_by('-publicar','-publicacao')[:3]

    return render_to_response('ingenium/destaque.html', locals(), context_instance=RequestContext(request))

def noticias(request):
    from publicacoes.models import Destaques,Noticias,Eventos
    from models import areavaga
    from datetime import datetime

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')[:3]
    noticias = Noticias.objects.all().order_by('-publicacao')
    paginator = Paginator(noticias, 10)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        noticias = paginator.page(page)
    except (EmptyPage, InvalidPage):
        noticias = paginator.page(paginator.num_page)

	
    return render_to_response('ingenium/noticias.html', locals(), context_instance=RequestContext(request),)

@csrf_protect
def noticia(request, slug):
    from models import areavaga,vaga
    from publicacoes.models import Destaques,Noticias

    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all().order_by('-pub_date')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')[:3]
    noticias = Noticias.objects.get(slug=slug)

    return render_to_response('ingenium/noticia.html', locals(), context_instance=RequestContext(request))


def login(request):
    from models import areavaga,empresa,usuario,vaga,procura
    from publicacoes.models import Artigo,Noticias,Destaques,Eventos,Parceiros,Enquete
    from publicidade.models import Publicidade
    from mensagens.models import mensagemUsuario, mensagemEmpresa
    from datetime import datetime
    noticias = Noticias.objects.all().order_by('-publicar', '-publicacao')[:3]
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    publicidade = Publicidade.objects.filter(data_entrada__lte=datetime.now()).order_by('-data_entrada')[:1]
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    areavaga = areavaga.objects.all().order_by('-qtdvagas')
    parceiros = Parceiros.objects.all()
    vagas = vaga.objects.all().order_by('-pub_date')
    empresas = empresa.objects.all()
    usuarios = usuario.objects.all()
    artigo = Artigo.objects.all().order_by('-publicar', '-publicacao')[:4]
    enquete = Enquete.objects.all().select_related().order_by('-data_publicacao')
    url = ''
    use = None
    emp = None
    mU = None
    mE = None
    ar = None
    vg = None
    eventos = None
    if request.POST.get('username'):
        user = request.POST.get('username')
        emp = empresa.objects.filter(username__icontains = user)
        if emp:
            emp = empresa.objects.get(username = user)
            url = '/painel-empresa-dashboard.html'
            mE = mensagemEmpresa.objects.filter(data__lte=datetime.now()).order_by('-data')
            eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')
        else:
            emp = usuario.objects.filter(email__icontains = user)
            if emp:
                emp = usuario.objects.get(email = user)
                url = '/painel-usuario-dashboard.html'
                mU = mensagemUsuario.objects.filter(data__lte=datetime.now()).order_by('-data')
                ar = procura.objects.filter(nome = emp)
                eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
                ab = ar.values('vaga')
                vg = vaga.objects.exclude(id__in = ab)
    if request.user.id:
        use = request.user.username
        uses = request.user.email
        emp = empresa.objects.filter(username__icontains = use)
        if emp:
            emp = empresa.objects.get(username = use)
            url = '/painel-empresa-dashboard.html'
            mE = mensagemEmpresa.objects.filter(data__lte=datetime.now()).order_by('-data')
            eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')
        else:
            emp = usuario.objects.filter(email__icontains = uses)
            if emp:
                emp = usuario.objects.get(email = uses)
                mU = mensagemUsuario.objects.filter(data__lte=datetime.now()).order_by('-data')
                url = '/painel-usuario-dashboard.html'
                ar = procura.objects.filter(nome = emp)
                ab = ar.values('vaga')
                vg = vaga.objects.exclude(id__in = ab)
                eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
        return render_to_response('ingenium'+url,context_instance=RequestContext(request, {'u':emp,'e':emp,'areavaga':areavaga,'mU':mU,'mE':mE,'ar':ar,'eventos':eventos, 'vg':vg}))

    if request.POST:
        emailUser = request.POST.get('username')
        senhaUser = request.POST.get('password')
        vaga = vaga.objects.all().order_by('-pub_date')
        eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
        u = authenticate(username=emailUser, password=senhaUser)
        if u is not None:
           if u.is_active:
               authlogin(request, u)

               return render_to_response('ingenium'+url, context_instance=RequestContext(request,{'u':emp,'e':emp,'areavaga':areavaga,'mU':mU,'mE':mE,'eventos':eventos,'vg':vg,'ar':ar}))

    return render_to_response('ingenium/index.html',locals(), context_instance=RequestContext(request, {'erro':'Dados Invalidos!'}))

def procura(request, vag_id):
    from models import usuario,areavaga,vaga,procura
    import datetime
    u = usuario.objects.get(pk=vag_id, user=request.user,)
    areavaga = areavaga.objects.all()
    vagas = vaga.objects.values_list('id', flat = True)
    vg = None
    p = None
    teste = None
    teste2 = None
    qtd = None
    i = None
    us = request.user
    use = usuario.objects.filter(email__exact = us)
    use = use.get()
    use = use.id
    for i in vagas:
        qtd = 1
        if ('vaga'+str(i)) in request.POST:
            p = procura.objects.get_or_create(nome_id = use,vaga_id = i,data = datetime.datetime.now())
        qtd += 1
    proc = procura.objects.filter(nome__id__exact = use)
    return render_to_response('ingenium/resultado-condidata.html',locals(),context_instance=RequestContext(request, {'areavaga':areavaga,'quant':use, 'bus':vg, 'are':request.POST, 'pro':p,'qtd':qtd,'teste':teste,'teste2':teste2,'i':i,'proc':proc}))

def procura2(request):
    from models import usuario,areavaga,vagaempresa, procura
    v = vagaempresa.objects.all()
    if request.user.id:
        ide = request.user.id
        u = usuario.objects.filter(user__exact=ide).values_list('id',flat = True)[:1]
        areavaga = areavaga.objects.all()
        vg = None
        p = None
        usuari = None
        teste = None
        teste2 = None
        use = None
        proc = None
        for use in u:
            usuari = usuario.objects.get(id=use)
            p = procura.objects.get_or_create(nome_id = use,vaga_id = int(request.POST['vaga']))
            proc = procura.objects.filter(nome__id__exact = use)
        return render_to_response('ingenium/ultimasvagas.html',locals(),context_instance=RequestContext(request, {'areavaga':areavaga,'quant':use, 'bus':vg, 'are':request.POST, 'pro':p,'teste':teste,'teste2':teste2,'proc':proc,'u':usuari}))


def sair(request):
    logout(request)
    return redirect('/index/')

def contato(request):
    from ingenium.models import areavaga
    from forms import FormContato

    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = FormContato(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = FormContato()
    else:
        form = FormContato()	
	
    return render_to_response('ingenium/contato.html',locals(),context_instance=RequestContext(request),)



def buscae(request):
    from models import vaga,areavaga,vagaempresa
    from publicacoes.models import Eventos,Destaques
    from datetime import datetime
    vaga = vaga.objects.all().order_by('-pub_date')
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    areavaga = areavaga.objects.all()
    quant = 0
    if request.GET['keyword']!='' or request.GET['id_vaga_descricao']!='':
        itens = vagaempresa.objects.filter(vaga__descricao__icontains = request.GET['keyword'],vaga__area__areaatuacao__icontains = request.GET['id_vaga_descricao'])
        if itens:
            quant = itens.count()

        c = Context({'itens_busca': itens, 'quant':quant, 'bus':request.GET['keyword'],'are':request.GET['id_vaga_descricao']})
        return render_to_response('ingenium/resultado-busca.html', locals() ,context_instance=RequestContext(request,c))


    return render_to_response('ingenium/index.html', locals(), context_instance=RequestContext(request,{'msg':'Por Favor, preencha pelo menos um campo de busca!'}))

def buscap(request):
    from models import areavaga,vaga
    from publicacoes.models import Destaques,Eventos
    from datetime import datetime
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all().order_by('-pub_date')

    quante = 0
    if  request.GET['keywordp']!='' or request.GET['id_select']!='':
        ites = procura.objects.filter(vaga__descricao__icontains = request.GET['keywordp'],vaga__area__areaatuacao__icontains = request.GET['id_select']).filter(nome__tipoperfil__icontains='2')
        if ites:
            quante = ites.count()
        c = Context({'itens_busca': ites, 'quant':quante, 'bus':request.GET['keywordp'], 'are':request.GET['id_select']})
        return render_to_response('ingenium/busca.html', locals() ,context_instance=RequestContext(request,c))


    return render_to_response('ingenium/index.html', locals() ,context_instance=RequestContext(request,{'msg':'Por Favor, preencha pelo menos um campo de busca!'}))

def page_not_found(request):
    return render_to_response('ingenium/404.html', locals(), context_instance=RequestContext(request))


def password_reset(request):
    if not request.user.is_authenticated():
        return django.contrib.auth.views.password_reset(request,
            template_name='ingenium/password_reset.html',
            email_template_name= 'ingenium/password_reset_email.html')
    else:
        return HttpResponseRedirect("/user/")

def cadastrocurso(request,curso_id):

    from ingenium.models import areavaga,curso
    from forms import inscricaoForm
    areavaga = areavaga.objects.all()
    cursos = curso.objects.get(id=curso_id)
    todoscursos = curso.objects.all()

    if request.method == 'POST':
        form = inscricaoForm(request.POST, request.FILES)
        if form.is_valid():
            novo_curso = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi39.tinypic.com/35d5now.jpg'/></a>"
            msg = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msg.content_subtype = "html"
            msg.send()
            return render_to_response('ingenium/cursoconcluido.html',locals(), context_instance=RequestContext(request))

    else:
        form = inscricaoForm()

    return render_to_response('ingenium/cadastrocurso.html', locals(), context_instance=RequestContext(request))
